<?php
defined('_JEXEC') or die('Restricted access');

class igUploadHelper
{
    function upload_file($fileName, $tmpPath, $uploadError, $destDir, $refresh)
	{
		if( !igUploadHelper::checkFileError($uploadError, $fileName, $refresh) )
		{
		    return false;
		}
		
		if( !igUploadHelper::checkUploadLimit($refresh) )
		{
		    return false;
		}
		
		if( !igUploadHelper::checkMaxFilesize($tmpPath, $fileName, $refresh) )
		{
		    return false;
		}
		
		if( !igUploadHelper::checkExtension($fileName, $refresh) )
		{
		    return false;
		}
		
		if( !igUploadHelper::checkMime($tmpPath, $refresh) )
		{
		    return false;
		}
		
		$fileNameClean = igUploadHelper::replaceSpecial($fileName);
		
		$fileNameUnique = igUploadHelper::makeUniqueName($destDir, $fileNameClean);
		
		if( !igUploadHelper::moveFile($tmpPath, $destDir, $fileNameUnique, $refresh) )
		{
		    return false;
		}

		return $fileNameUnique;
	}
	
	function checkFileError($uploadError, $fileName, $refresh)
	{
		if ($uploadError > 0)
		{
			switch ($uploadError)
			{
				case 1:
					igFileHelper::raiseError('U1 '.$fileName . JText::_( 'FILE TO LARGE INI' ), $refresh);
					break;

				case 2:
					igFileHelper::raiseError('U2 '.$fileName . JText::_( 'FILE TO LARGE HTML' ), $refresh);
					break;

				case 3:
					igFileHelper::raiseError('U3 '.$fileName . JText::_( 'ERROR PARTIAL UPLOAD' ), $refresh);
					break;

				case 4:
					igFileHelper::raiseError('U4 '.$fileName . JText::_( 'ERROR NO FILE' ), $refresh);
					break;
				
				case 6:
					igFileHelper::raiseError('U6 '.$fileName . JText::_( 'Server is missing a temporary upload folder' ), $refresh);
					break;
					
				case 7:
					igFileHelper::raiseError('U7 '.$fileName . JText::_( 'Failed to write file to disk' ), $refresh);
					break;
					
				case 8:
					igFileHelper::raiseError('U8 '.$fileName . JText::_( 'A PHP extension stopped the file upload' ), $refresh);
					break;
					
				default:
					igFileHelper::raiseError('U4a '.$fileName . JText::_( 'UPLOAD ERROR CODE' ).': '.$uploadError, $refresh);
			}
			return false;
		}
		
		return true;
	}
	
	function checkUploadLimit($refresh)
	{
	    $user =& JFactory::getUser();
	    $db   =& JFactory::getDBO();
	    $configArray =& JComponentHelper::getParams('com_igallery');
	    
		if( $user->get('aid', 0) < 2)
		{
			$query = 'SELECT * FROM #__igallery_img WHERE user = '.(int)$user->id;
			$db->setQuery($query);
			$db->query($query);
			$numRows = $db->getNumRows();
			if($numRows >= $configArray->get('max_upload_amount', 500))
			{
				igFileHelper::raiseError(JText::_( 'MAX AMOUNT IMAGES REACHED' ), $refresh);
				return false;
			}
		}
		
		return true;
	}
	
	function checkMaxFilesize($tmpPath, $fileName, $refresh)
	{
	    $configArray =& JComponentHelper::getParams('com_igallery');
	    
		$maxUploadSize = $configArray->get('max_upload_img', 1500) * 1000;
		$fileSize = filesize($tmpPath);
		
		if ($maxUploadSize < $fileSize)
		{
			igFileHelper::raiseError('U5 - '.$fileName .' - '.JText::_( 'FILESIZE' ).': '.$fileSize/1000 .'KB - '.
			JText::_( 'MAXIMUM FILESIZE' ).': '.$maxUploadSize/1000 .'KB - '. JText::_( 'FILE TO LARGE' ), $refresh);
			return false;
		}
		
		return true;
	}
	
	function checkExtension($fileName, $refresh, $errorRaise = true)
	{
	    $extAccept = 'jpeg,jpg,png,gif';
		$validFileExts = explode(",", $extAccept);
		$uploadedFileExtension = JFile::getExt($fileName);
		$extOk = false;

		foreach($validFileExts as $key => $value)
		{
			if( preg_match("/$value/i", $uploadedFileExtension ) )
			{
				$extOk = true;
			}
		}

		if ($extOk == false)
		{
			if($errorRaise == true)
			{
				igFileHelper::raiseError('U6b '. JText::_( 'INCORRECT FILETYPE' ). ', Filetype: '.$uploadedFileExtension.
				', Allowed: '. $extAccept, $refresh);
				return false;
			}
		}
		
		return true;
	}
	
	function checkMime($tmpPath, $refresh)
	{ 
		$mimeAccept = 'image/jpeg,image/pjpeg,image/png,image/x-png,image/gif';
		$validFileTypes = explode(",", $mimeAccept);
		$imageinfo = getimagesize($tmpPath);

		if( !is_int($imageinfo[0]) || !is_int($imageinfo[1]) ||  !in_array($imageinfo['mime'], $validFileTypes) )
		{
			igFileHelper::raiseError('U6c '. JText::_( 'INCORRECT FILETYPE' ). ' , Uploaded Filetype: '.$imageinfo[0].' '.$imageinfo[1].' '.$imageinfo['mime'].
			', Allowed: '. $mimeAccept, $refresh);
			return false;
		}
		
		return true;
	}
	
	function replaceSpecial($fileName)
	{
	    $fileExt = JFile::getExt($fileName);
	    $fileNameNoExt = JFile::stripExt($fileName);
		$fileNameNoExt = preg_replace('/[^A-Za-z0-9.]/', '_', $fileNameNoExt);
		$fileName = $fileNameNoExt.'.'.$fileExt;
		
		return $fileName; 
	}
	
	function makeUniqueName($destDir, $fileName)
	{
	    $fileExt = JFile::getExt($fileName);
	    $fileNameNoExt = JFile::stripExt($fileName);
	    
		if(JFile::exists($destDir.$fileName) )
		{
			$i=1;
			while(JFile::exists($destDir.$fileNameNoExt.$i.'.'.$fileExt) )
			{
				$i++;
			}
			$fileName = $fileNameNoExt.$i.'.'.$fileExt;
		}
		
		return $fileName;
	}
	
	function moveFile($tmpPath, $destDir, $fileName, $refresh)
	{
		$destPath = $destDir.DS.$fileName;
		
		if(!JFile::upload($tmpPath, $destPath))
		{
			igFileHelper::raiseError('U7 '. $tmpPath.' -> '.$destPath .' '. JText::_( 'ERROR MOVING FILE' ), $refresh);
			return false;
		}
		
		return true;
	}
	
	
}

?>